<?php
/**
 * QrCodeController.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-04 10:54:16
 * @modified    2023-02-04 10:54:16
 *
 */

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\Event;
use App\Models\Product;
use App\Models\Product\QrCode;
use App\Repositories\Customer\EventRepo;
use App\Repositories\OperationLogRepo;
use App\Services\VerifyCodeServ;
use Illuminate\Http\Request;

class QrCodeFrontController extends Controller
{
    public function index(Request $request)
    {
        $qrcodeId = request()->query('qrcode_id') ?? 0;
        $qrcode = QrCode::with('product.type')->find($qrcodeId);
        $title = 'qrcode';
        $productId = $qrcode->product->id ?? 0;
        $product = Product::with(['customer'])->find($productId);
        if ($product) {
            $title = $product->name;
        }

        $data = [
            'qrcode_id' => $qrcodeId,
            'qrcode' => $qrcode,
            'product_id' => $productId,
            'product' => $product,
            'title' => $title,
            'type_repair' => EventRepo::TYPE_REPAIR,
            'type_complain' => EventRepo::TYPE_COMPLAIN
        ];
        return view('pages.qrcode.index', $data);
    }

    public function repair(Request $request)
    {
        $qrcodeId = request()->query('qrcode_id') ?? 0;
        $type = request()->query('type') ?? '';
        $types = array_keys(collect(EventRepo::params()['types'])->keyBy('code')->toArray());
        if (!in_array($type, $types)) {
            $type = EventRepo::TYPE_REPAIR;
        }
        $qrcode = QrCode::with('product.type')->find($qrcodeId);
        $productId = $qrcode->product->id ?? 0;
        $product = Product::with(['customer.user'])->find($productId);
        $accountSession = session()->get(VerifyCodeServ::CODE_KEY);
        if (empty($accountSession)) {
            $route = 'account/login?redirect=qrcode/repair?qrcode_id=' . $qrcodeId . '&type=' . $type;
            return response()->redirectTo($route);
        }
        $types = collect(EventRepo::params()['types'])->keyBy('code')->toArray();
        $typeText = $types[$type]['title'] ?? '';

        $headTitle = '故障信息';
        $descTitle = '故障描述';
        $noImageTitle = '无故障图片';
        $imageTitle = '故障图片';

        if ($type == EventRepo::TYPE_COMPLAIN) {
            $headTitle = '投诉建议信息';
            $descTitle = '情况说明';
            $noImageTitle = '无图片';
            $imageTitle = '图片';
        }

        $data = [
            'qrcode_id' => $qrcodeId,
            'account' => $accountSession,
            'qrcode' => $qrcode,
            'product_id' => $productId,
            'product' => $product,
            'type' => $type,
            'type_text' => $typeText,
            'head_title' => $headTitle,
            'desc_title' => $descTitle,
            'img_title' => $imageTitle,
            'no_image' => $noImageTitle
        ];
        return view('pages.qrcode.repair', $data);
    }

    public function store(Request $request)
    {
        return message('提交成功');
        $data = $request->all();
        $sessionAccount = session()->get(VerifyCodeServ::CODE_KEY);
        if (!$sessionAccount){
            throw new \Exception('请先登录');
        }
        $number = EventRepo::generateNumber(0);
        $type = $request->get('type', '');

        $types = array_keys(collect(EventRepo::params()['types'])->keyBy('code')->toArray());
        if (!in_array($type, $types)) {
            $type = EventRepo::TYPE_REPAIR;
        }

        $qrcodeId = $request->get('qrcode_id', 0);
        $qrcode = QrCode::with('product.customer')->findOrFail($qrcodeId);
        $productCustomerUserId = $qrcode->product->customer->customer_user_id ?? 0;
        $customerUser = Customer\User::find($productCustomerUserId);
        $customerUserId = $customerUser->id ?? 0;
        $customerId = intval($qrcode->product->customer->id ?? 0);
        $contactName = strval($data['contact_name'] ?? '');
        $eventData = [
            'event_number' => $number,
            'type' => $type,
            'customer_id' => $customerId,
            'customer_user_id' => intval($productCustomerUserId ?? 0),
            'product_id' => intval($qrcode->product->id),
            'created_by' => intval($customerUserId ?? 0),
            'created_type' => EventRepo::CREATED_TYPE_CUSTOMER,
            'status' => EventRepo::STATUS_UN_DISTRIBUTE,
            'description' => strval($request->get('description', '')),
            'contact_name' => $contactName,
            'contact_telephone' => strval($data['contact_telephone'] ?? ''),
            'address' => strval($data['address'] ?? ''),
        ];
        $imgs = $request->get('imgs') ?? [];
        $eventImages = [];
        if ($imgs) {
            foreach ($imgs as $img) {
                if (trim($img)) {
                    $eventImages[] = trim($img);
                }
            }
        }

        // 发送通知，记录 Log
        $creatorName = $qrcode->product->customer->name ?? $contactName;
        $action = "提交了事件 #{$number}";

        $bodyData = [
            'creator' => $creatorName,
            'action' => $action
        ];
        OperationLogRepo::createLog(OperationLogRepo::BUSINESS_TYPE_EVENT, 1, json_encode($bodyData));
        $event = new Event();
        $event->fill($eventData);
        $event->saveOrFail();

        $images = [];
        if ($eventImages) {
            foreach ($eventImages as $eventImage) {
                $images[] = new Event\Image(['img' => $eventImage]);
            }
        }

        if ($images) {
            $event->images()->saveMany($images);
        }

        return response()->json(['status' => 'ok']);
    }
}